use bracket_lib::prelude::*;
use image::*;

pub struct Player {
    pub x: i32,
    pub y: i32,
    velocity: f32,
    img: DynamicImage, // 新增图片字段
}

impl Player {
    pub fn new(x: i32, y: i32) -> Self {
        Player {
            x,
            y,
            velocity: 0.0,
            img: image::open("assets/player.png").unwrap(), // 加载图片
        }
    }
    pub fn render(&self, ctx: &mut BTerm, camera_x: i32) {
        let (img_width, img_height) = self.img.dimensions();
        let screen_x = self.x - camera_x;
        // 恢复为6x6像素区域显示图片
        for dx in 0..6 {
            for dy in 0..6 {
                let px = screen_x + dx;
                let py = self.y + dy;
                if px >= 0 && px < 120 && py >= 0 && py < 80 {
                    // 将6x6区域映射到图片的对应位置
                    let img_x = (dx as f32 / 6.0 * img_width as f32) as u32;
                    let img_y = (dy as f32 / 6.0 * img_height as f32) as u32;
                    let img_x = img_x.min(img_width - 1);
                    let img_y = img_y.min(img_height - 1);
                    let pixel = self.img.get_pixel(img_x, img_y);
                    ctx.set_bg(px, py, (pixel[0], pixel[1], pixel[2]));
                }
            }
        }
    }
    pub fn gravity_and_move(&mut self) {
        // 增加重力加速度，让下落更快
        if self.velocity < 4.0 {
            self.velocity += 0.4
        }
        self.y += self.velocity as i32;
        self.x += 1;

        if self.y < 0 {
            self.y = 0;
            self.velocity = 0.0; // 碰到顶部时重置速度
        }
    }
    pub fn flap(&mut self) {
        // 增加向上跳跃的初始速度
        self.velocity = -3.0
    }
}
